const Database = require('better-sqlite3')
class Engine {
    #db
    #smt
    constructor() {
        this.#db = new Database('./db.sqlite3', { verbose: this.showMessage })
    }
    excute(sql, params_obj) {
        this.#smt = this.#db.prepare(sql)
        let is_vaild_params = this.ISVailid(params_obj)
        let response = {}
        is_vaild_params
            ? response = this.#smt.run()
            : response = this.#smt.run(params_obj)
        return response
    }
    query(sql, params_obj) {
        this.#smt = this.#db.prepare(sql)
        let is_vaild_params = this.ISVailid(params_obj)
        let response = {}
        is_vaild_params
            ? response = this.#smt.get()
            : response = this.#smt.get(params_obj)
        return response
    }
    query_all(sql, params_obj) {
        this.#smt = this.#db.prepare(sql)
        let is_vaild_params = this.ISVailid(params_obj)
        let response = {}
        is_vaild_params
            ? response = this.#smt.all()
            : response = this.#smt.all(params_obj)
        return response
    }
    close() {
        this.#db.close()
    }
    ISVailid(params_obj) {
        return params_obj === null || params_obj === {} || params_obj === []
    }

    showMessage(msg) {
        console.log(msg)
    }
}

var engine = new Engine()
// 每次导入的时候先检查以下数据库是否存在相应的表结构，
let res = engine.excute("SELECT count(*) FROM sqlite_master WHERE type=''table' AND name = 'book'", null)
console.log(res)
engine.close()


module.exports = Engine




// var engine = new Engine()

// engine.excute("create table book (id int, name varchar(20))")
// engine.excute("insert into book values(@id,@name)", {
//     id: 2,
//     name: "洛神赋2"
// })
// engine.excute("insert into book values($id,$name)", {
//     id: 3,
//     name: "洛神赋3"
// })
// let res1 = engine.query("select * from book where id = ?", 1)
// let res2 = engine.query_all('select * from book', null)
// console.log(res1)
// console.log(res2)
// engine.close()
